// miniprogram/pages/index/index.js
const date = require('../../utils/date.js');
const regeneratorRuntime = require("../../lib/runtime");
let app=getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    step: '正在获取数据...',//今日运动步数
    jf: '正在获取数据...',//今日运动积分
    totalJf: '正在获取数据...',//运动总积分
    runDays: '正在获取数据...',//运动天数
    userInfo: null,
    goldcoins:0,//金币数
    signStatus: {
      singImg: '../../images/qd.png',
      text: '签到',
      qdDay: '正在获取数据...',
      totalJf: '正在获取数据...',
    },
    jfdh:[
      {
        cid:0,
        name:'签到积分'
      },
      {
        cid:1,
        name:'运动积分'
      }
    ],
    ridioValue:0,
    popShow:false,
    allRecharge:0,
    userCloudID:'',
    ycolor: 'y-blue',
    newReceive:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let fop = '';
    this.yxbh();//让邮箱闪烁
    if (options.openid != undefined) {
      fop = options.openid;
      this.getUserInfo(fop);
    }
  },

  /**
   * 检查是否有新邮件
   */
  ckyx(){
    wx.cloud.callFunction({
      name: 'receiveGift',
    }).then(res => {
      //console.log(res.result)
      if(!res.result){
        return;
      }
      let newReceive = res.result;
      if (newReceive.length == 0) {
        newReceive=null
      }
      this.setData({
        newReceive
      });
    })
  },

  /**
   * 令邮箱闪烁的时间器
   */
  yxbh(){
    setInterval(()=>{
      let ycolor=(this.data.ycolor=='y-blue')?'y-orange':'y-blue';
      this.setData({
        ycolor
      })
    },200)
  },
  
  /**
   * 查看邮箱信息
   */
  catyx(){
    let newReceive=this.data.newReceive;
    let data=JSON.stringify(newReceive);
    wx.navigateTo({
      url: '../yxlist/yxlist?data='+data,
    })
  },

  async getUserInfo(fop='') {
    let that = this;
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            lang:'zh_CN',
            success: function(res) {
              //console.log(res.cloudID);
              that.setData({
                userInfo: res.userInfo,
                userCloudID: res.cloudID
              });
              app.globalData.userInfo=res.userInfo;
              if(fop){that.friendShare(res.cloudID,fop)}
              that.friend(res.cloudID)
              that.getRunData();
            }
          })
        }
      }
    })
  },


  async friendShare(id,fop){
   await wx.cloud.callFunction({
      name: 'initFriend',
      data: {
        userData: wx.cloud.CloudID(id)
      }
    });

    await wx.cloud.callFunction({
      name:'friend',
      data:{
        fop,
        act:'share'
      }
    })
  },
  /**
   * 授权用户信息
   */
   async bindGetUserInfo(e) {
    //console.log(e.detail.userInfo);
    this.setData({
      userInfo: e.detail.userInfo
    });
    this.getUserInfo();
  },

  /**
   * 获取微信步数
   */
   async getRunData() {
    let that=this;
    wx.login({
      async success(res0){
        wx.getWeRunData({
         async success(res1){
            //console.log(res1);
          that.upDatePhbStep(res1.cloudID);
          let res= await wx.cloud.callFunction({
              name: 'getRunData',
              data: {
                weRunData: wx.cloud.CloudID(res1.cloudID)
              }
            })
              //console.log(res.result);
              let stepInfoList = res.result;
              let runDays = res.result.runDays;
              let jf = res.result.jf;
              let totalJf = res.result.totalJf;
              let step = res.result.step;
              let obj = {
                runDays,
                jf,
                totalJf,
                step
              }
              that.get_sign(obj);
              wx.stopPullDownRefresh();
          }
        })
      }
    })
  },

  /**
   * 刷新数据
   */
  reData() {
    this.setData({
      step: '正在获取数据...',
      jf: '正在获取数据...',
      totalJf: '正在获取数据...',
      runDays: '正在获取数据...',
      ['signStatus.qdDay']:'正在获取数据...',
      ['signStatus.totalJf']:'正在获取数据...'
    });
    this.getRunData();
  },

  /**
   * 获取签到状态
   */
  async get_sign(obj) {
    let res= await wx.cloud.callFunction({
      name: 'sign',
      data: {
        action: 'get'
      }
    });
      //console.log(res.result);
      let signData = res.result.signData;
      this.setData({
        runDays:obj.runDays,
        jf:obj.jf,
        totalJf:obj.totalJf,
        step:obj.step,
        signStatus: {
          singImg: signData.status ? '../../images/yqd.png' : '../../images/qd.png',
          text: signData.status ? '已签到' : '签到',
          qdDay: signData.totalDays,
          totalJf: signData.totalJf
        },

      });
  },

  /**
   * 进行签到操作
   */
  async sign() {
    if (this.data.signStatus.text=='已签到'){
      return;
    }
    wx.showLoading({
      title: '正在签到',
    });
    let res=await wx.cloud.callFunction({
      name: 'sign',
      data: {
        action: 'add'
      }
    })
      //console.log(res.result);
      let signData = res.result.signData;
      if (res.result.code == 0) {
        wx.showToast({
          title: '签到成功,积分+66！',
          icon: 'none'
        })
        this.setData({
          signStatus: {
            singImg: signData.status ? '../../images/yqd.png' : '../../images/qd.png',
            text: signData.status ? '已签到' : '签到',
            qdDay: signData.totalDays,
            totalJf: signData.totalJf
          },

        });
      } else {
        wx.showToast({
          title: res.result.errorMes,
          icon: 'none'
        })
      }

  },

  radioChange(e){
    let cid=Number(e.detail.value);
    //console.log(cid);
    this.setData({
      ridioValue:cid
    })
  },

  /**
   * 积分兑换金币
   */
  duihuan(e){
    //console.log(e.detail.value);
    var{jfNum,jfClass}=e.detail.value;
    jfNum=Number(jfNum);
    jfClass=Number(jfClass);
    if(jfNum==''){
      wx.showModal({
        title: '提示',
        content: '请输入积分数量',
        showCancel:false
      });
      return;
    }
    if (jfNum > (jfClass == 0 ? this.data.signStatus.totalJf:this.data.totalJf)){
      wx.showModal({
        title: '提示',
        content: '输入的积分数超过拥有的积分数',
        showCancel:false
      });
      return;
    }

    wx.showLoading({
      title: '正在兑换',
    });

    wx.cloud.callFunction({
      name:'DuiHuan',
      data:{
        type:jfClass,
        num:jfNum
      }
    }).then(res=>{
      //console.log(res.result);
      let stu=res.result;
      if(stu.code==0){
        if(jfClass==0){
          this.setData({
            goldcoins:this.data.goldcoins+jfNum,
            ['signStatus.totalJf']:this.data.signStatus.totalJf-jfNum
          })
        }
        else{
          this.setData({
            goldcoins: this.data.goldcoins + jfNum,
            totalJf: this.data.totalJf-jfNum,
          })
        }
      }
      wx.showToast({
        title: stu.mes,
      });
      this.setData({
        popShow:false
      })
      this.popHide();
    })
  },

  getGoldcoins(){
    wx.cloud.callFunction({
      name:'getGold'
    }).then(res=>{
      //console.log(res.result);
      this.setData({
        goldcoins:res.result.goldNum
      });
    })
  },

  async getAllRecahrge(){
    let res= await wx.cloud.callFunction({
        name:'getRecord'
    });
    if(res.result.code==0){
      this.setData({
        allRecharge:res.result.data.sum
      })
    }
  },

  popShow(){
    this.setData({
      popShow:true
    })
  },

  popHide(){
    this.setData({
      popShow:false
    })
  },

  toRecharge(){
    wx.navigateTo({
      url: '../recharge/recharge',
    })
  },
  toRecord() {
    wx.navigateTo({
      url: '../record/record',
    })
  },

  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.ckyx();//检查是否有新邮件
    //每10秒检查一次
    setInterval(() => {
      this.ckyx()
    }, 20000);
    this.getUserInfo();
    // this.getRunData();
    this.getGoldcoins();
    // this.get_sign();
    this.getAllRecahrge();
  },

  /**
   * 初始化排行榜数据
   */
  upDatePhbStep:function(id){
    wx.cloud.callFunction({
      name:'updatePhbStep',
      data: {
        weRunData: wx.cloud.CloudID(id),
        userData:wx.cloud.CloudID(this.data.userCloudID)
      }
    });
  },

  /**
   * 初始化好友列表数据
   */
  friend(id){
    wx.cloud.callFunction({
      name:'initFriend',
      data:{
        userData: wx.cloud.CloudID(id)
        }
    })
  },



  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.reData();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})